﻿using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.Display;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.esriSystem;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;



namespace MyMap
{
    public partial class BarChartThematicMapForm : Form
    {

        // 从主窗体传入的原始目标图层
        private IFeatureLayer _originalFeatureLayer;
        // 从主窗体传入的地图控件，用于刷新
        private AxMapControl _mapControl;

        // 用于存储用户选择的字段和设置
        private List<string> _selectedFields;
        private int _symbolWidth;
        private int _symbolHeight;

        public BarChartThematicMapForm()
        {
            InitializeComponent();
        }



        // 窗体构造函数：接收外部传入的要素图层和地图控件
        public BarChartThematicMapForm(IFeatureLayer targetLayer, AxMapControl mapControl)
        {
            InitializeComponent();
            _originalFeatureLayer = targetLayer ?? throw new ArgumentNullException(nameof(targetLayer));
            _mapControl = mapControl ?? throw new ArgumentNullException(nameof(mapControl));
        }

        private void BarChartThematicMapForm_Load(object sender, EventArgs e)
        {
            // 加载数值型字段到列表框
            List<string> numericFields = GetNumericFields(_originalFeatureLayer);
            listBoxUnselected.Items.AddRange(numericFields.ToArray());

            // 初始化尺寸输入框
            txtSymbolWidth.Text = "6";
            txtSymbolHeight.Text = "60";
        }

        // 前期定义的“筛选数值型字段”方法（复用）
        private List<string> GetNumericFields(IFeatureLayer featureLayer)
        {
            List<string> numericFields = new List<string>();
            IFields fields = featureLayer.FeatureClass.Fields;
            for (int i = 0; i < fields.FieldCount; i++)
            {
                IField field = fields.get_Field(i);
                if (field.Type == esriFieldType.esriFieldTypeInteger ||
                    field.Type == esriFieldType.esriFieldTypeDouble ||
                    field.Type == esriFieldType.esriFieldTypeSingle)
                {
                    numericFields.Add(field.Name);
                }
            }
            return numericFields;
        }



      


        // 生成柱状统计专题地图
        // 同时修改GenerateBarChartThematicMap方法，传递maxValue到CreateBarChartRenderer
        private void GenerateBarChartThematicMap(IFeatureLayer featureLayer, List<string> selectedFields, int symbolWidth, int symbolMaxHeight)
        {
            if (selectedFields == null || selectedFields.Count == 0)
                throw new ArgumentException("请至少选择一个数值型字段");

            double maxValue = 0;
            foreach (string field in selectedFields)
            {
                double fieldMax = GetFieldMaxValue(featureLayer, field);
                if (fieldMax > maxValue) maxValue = fieldMax;
            }

            IBarChartSymbol barChartSym = CreateBarChartSymbol(selectedFields, maxValue, symbolWidth, symbolMaxHeight);
            // 传递maxValue到CreateBarChartRenderer
            IChartRenderer chartRenderer = CreateBarChartRenderer(selectedFields, barChartSym, maxValue);

            IGeoFeatureLayer geoFeatureLayer = featureLayer as IGeoFeatureLayer;
            geoFeatureLayer.Renderer = chartRenderer as IFeatureRenderer;

            ILayer layer = featureLayer as ILayer;
            layer.Draw(esriDrawPhase.esriDPGeography, _mapControl.ActiveView.ScreenDisplay, null);

            EnsureBaseLayersVisible();

            
        }

        // 新增方法：强制显示底图图层
        private void EnsureBaseLayersVisible()
        {
            for (int i = 0; i < _mapControl.Map.LayerCount; i++)
            {
                ILayer layer = _mapControl.Map.get_Layer(i);
                // 根据你的底图图层名称调整关键词（如"World"、"Continents"等）
                if (layer.Name.Contains("World") || layer.Name.Contains("底图") ||
                    layer.Name.Contains("Continents") || layer.Name.Contains("行政区"))
                {
                    layer.Visible = true;
                }
            }
        }

        // 统计指定字段的最大值
        private double GetFieldMaxValue(IFeatureLayer featureLayer, string fieldName)
        {
            IFeatureClass featureClass = featureLayer.FeatureClass;
            IDataStatistics dataStats = new DataStatisticsClass();
            dataStats.Field = fieldName;
            // 设置数据游标
            IFeatureCursor featureCursor = featureClass.Search(null, false);
            dataStats.Cursor = (ICursor)featureCursor;
            // 使用正确的接口名称IStatisticsResults
            IStatisticsResults statsResults = dataStats.Statistics;
            System.Runtime.InteropServices.Marshal.ReleaseComObject(featureCursor);
            return statsResults.Maximum;
        }

        // 创建柱状图符号
        private IBarChartSymbol CreateBarChartSymbol(List<string> selectedFields, double maxValue, int symbolWidth, int symbolHeight)
        {
            IBarChartSymbol barChartSym = new BarChartSymbolClass();

            // 设置符号尺寸
            IMarkerSymbol markerSym = (IMarkerSymbol)barChartSym;
            markerSym.Size = symbolHeight;
            barChartSym.Width = symbolWidth;

            // 定义颜色数组（确保颜色正确实例化）
            IRgbColor[] colors = new IRgbColor[]
            {
                CreateRgbColor(255, 0, 0),    // 红色
                CreateRgbColor(0, 255, 0),    // 绿色
                CreateRgbColor(0, 0, 255),    // 蓝色
                CreateRgbColor(255, 255, 0),  // 黄色
                CreateRgbColor(255, 165, 0)   // 橙色
            };

            // 添加符号到柱状图（使用ISymbolArray接口）
            ISymbolArray symbolArray = (ISymbolArray)barChartSym;
            for (int i = 0; i < selectedFields.Count; i++)
            {
                ISimpleFillSymbol fillSym = new SimpleFillSymbolClass();
                fillSym.Style = esriSimpleFillStyle.esriSFSSolid;
                fillSym.Color = colors[i % colors.Length]; // 循环使用颜色
                symbolArray.AddSymbol(fillSym as ISymbol);
            }

            // 设置最大值（控制柱子高度比例）
            IChartSymbol chartSym = (IChartSymbol)barChartSym;
            chartSym.MaxValue = maxValue;

            return barChartSym;

        }

        // 创建柱状图渲染器
        // 同时修改CreateBarChartRenderer方法，将MaxValue设置到IChartRenderer中
        private IChartRenderer CreateBarChartRenderer(List<string> selectedFields, IBarChartSymbol barChartSym, double maxValue)
        {
            IChartRenderer chartRenderer = new ChartRendererClass();
            chartRenderer.ChartSymbol = (IChartSymbol)barChartSym;
            chartRenderer.UseOverposter = true;

            // 设置渲染字段
            IRendererFields rendererFields = chartRenderer as IRendererFields;
            rendererFields.ClearFields();
            foreach (string field in selectedFields)
            {
                rendererFields.AddField(field, field);
            }

            return chartRenderer;
        }

        // 辅助方法：创建RGB颜色
        private IRgbColor CreateRgbColor(int r, int g, int b)
        {
            IRgbColor color = new RgbColorClass();
            color.Red = r;
            color.Green = g;
            color.Blue = b;
            color.Transparency = 0;
            return color;
        }



        private void BtnOK_Click(object sender, EventArgs e)
        {
            if (!ValidateUserInput())
            {
                return;
            }

            try
            {
                // 手动创建新图层（替代IClone克隆）
                IFeatureLayer chartLayer = new FeatureLayerClass();
                chartLayer.FeatureClass = _originalFeatureLayer.FeatureClass; // 复用原始图层的要素类
                chartLayer.Name = _originalFeatureLayer.Name + "_柱状图";

                // 计算最大值
                double maxValue = _selectedFields.Max(field => GetFieldMaxValue(_originalFeatureLayer, field));

                // 应用柱状图渲染器
                DefineBarChartRenderer(chartLayer, _selectedFields, maxValue, _symbolWidth, _symbolHeight);

                // 添加新图层到地图
                _mapControl.Map.AddLayer(chartLayer);

                // 刷新
                _mapControl.ActiveView.Refresh();
                MessageBox.Show("柱状统计专题地图生成成功！");
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"生成柱状图失败: {ex.Message}");
            }
        }


        /// <summary>
        /// 仿照你的代码，为指定图层定义柱状图渲染器
        /// </summary>
        private void DefineBarChartRenderer(IFeatureLayer chartLayer, List<string> selectedFields, double maxValue, int symbolWidth, int symbolHeight)
        {
            // 1. 创建柱状图符号
            IBarChartSymbol barChartSym = CreateBarChartSymbol(selectedFields, maxValue, symbolWidth, symbolHeight);

            // 2. 创建图表渲染器
            IChartRenderer chartRenderer = new ChartRendererClass();
            chartRenderer.ChartSymbol = (IChartSymbol)barChartSym;
            chartRenderer.UseOverposter = true; // 防止标签重叠

            // 3. 设置渲染器的字段
            IRendererFields rendererFields = chartRenderer as IRendererFields;
            rendererFields.ClearFields();
            foreach (string field in selectedFields)
            {
                rendererFields.AddField(field, field);
            }

            // 4. 将渲染器应用到新复制的图层上
            IGeoFeatureLayer geoFeatureLayer = chartLayer as IGeoFeatureLayer;
            geoFeatureLayer.Renderer = chartRenderer as IFeatureRenderer;
        }


        /// <summary>
        /// 校验用户输入的合法性
        /// </summary>
        private bool ValidateUserInput()
        {
            if (listBoxSelected.Items.Count == 0)
            {
                MessageBox.Show("请至少选择一个数值型字段！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }

            if (!int.TryParse(txtSymbolWidth.Text, out _symbolWidth) || _symbolWidth <= 0)
            {
                MessageBox.Show("请输入有效的符号宽度（正整数）！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtSymbolWidth.Focus();
                return false;
            }

            if (!int.TryParse(txtSymbolHeight.Text, out _symbolHeight) || _symbolHeight <= 0)
            {
                MessageBox.Show("请输入有效的符号高度（正整数）！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtSymbolHeight.Focus();
                return false;
            }

            // 存储用户选择的字段
            _selectedFields = listBoxSelected.Items.Cast<string>().ToList();
            return true;
        }



        // 取消按钮：关闭界面
        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }



        private void BtnAdd_Click(object sender, EventArgs e)
        {
            // 遍历未选择列表中选中的字段
            foreach (var selectedItem in listBoxUnselected.SelectedItems.Cast<string>().ToList())
            {
                // 避免重复添加
                if (!listBoxSelected.Items.Contains(selectedItem))
                {
                    listBoxSelected.Items.Add(selectedItem);
                }
                // 从“未选择”列表中移除
                listBoxUnselected.Items.Remove(selectedItem);
            }
        }

        private void BtnRemove_Click(object sender, EventArgs e)
        {
            // 遍历已选择列表中选中的字段
            foreach (var selectedItem in listBoxSelected.SelectedItems.Cast<string>().ToList())
            {
                // 避免重复添加
                if (!listBoxUnselected.Items.Contains(selectedItem))
                {
                    listBoxUnselected.Items.Add(selectedItem);
                }
                // 从“已选择”列表中移除
                listBoxSelected.Items.Remove(selectedItem);
            }
        }



    }
}
